package org.intrasearch.core;

import com.google.common.collect.ImmutableSortedSet;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;

public class InvertedIndexArtifactIdCollection implements Externalizable
{
    private SortedSet<ArtifactId> artifactIds;

    private InvertedIndexArtifactIdCollection(ImmutableSortedSet<ArtifactId> artifactIds)
    {
        this.artifactIds = artifactIds;
    }

    public InvertedIndexArtifactIdCollection(Collection<ArtifactId> artifactIds)
    {
        this(ImmutableSortedSet.copyOf(artifactIds));
    }

    public InvertedIndexArtifactIdCollection merge(InvertedIndexArtifactIdCollection collection)
    {
        TreeSet<ArtifactId> treeSet = new TreeSet<ArtifactId>(artifactIds);
        treeSet.addAll(collection.artifactIds);
        return new InvertedIndexArtifactIdCollection(ImmutableSortedSet.copyOfSorted(treeSet));
    }

    public Collection<ArtifactId> getArtifactIds()
    {
        return artifactIds;
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {
        out.writeInt(artifactIds.size());
        for (ArtifactId artifactId : artifactIds)
        {
            out.writeObject(artifactId);
        }
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    {
        int size = in.readInt();
        ArrayList<ArtifactId> artifactIdArrayList = new ArrayList<ArtifactId>();
        for (int i = 0; i < size; i++)
        {
            artifactIdArrayList.add((ArtifactId) in.readObject());
        }
        artifactIds = ImmutableSortedSet.copyOf(artifactIdArrayList);
    }
}
